package com.pri.chat.fragment;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DTBean;
import com.netease.nim.uikit.net.entity.MemberBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.MainActivity;
import com.pri.chat.R;
import com.pri.chat.activity.DTmsgActivity;
import com.pri.chat.activity.NetPicShowActivity;
import com.pri.chat.activity.OtherPeopleMsgActivity;
import com.pri.chat.activity.PeopleMsgActivity;
import com.pri.chat.activity.RecommendedInteractiveActivity;
import com.pri.chat.activity.ReleaseJuBaoAcctivity;
import com.pri.chat.activity.ShareMemberActivity;
import com.pri.chat.adapter.DTAdapter;
import com.pri.chat.application.APP;
import com.pri.chat.bean.KeyAndValueEntity;
import com.pri.chat.database.greendao.KeyAndValueEntityDao;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.event.EventTag;
import com.pri.chat.event.MessageEvent;
import com.pri.chat.model.DTModel;
import com.pri.chat.model.SayModel;
import com.pri.chat.model.ZanModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.GpsUtil;
import com.pri.chat.utils.StringUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.fragment.FragmentLazy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.w3c.dom.Text;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/7
 */
public class DTFragment extends FragmentLazy implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.none)
    ImageView none;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;

    @BindView(R.id.inviteLinear)
    View inviteLinear;
    @BindView(R.id.tv_qkq)
    View tv_qkq;

    @BindView(R.id.ll_recommend)
    LinearLayout ll_recommend;
    @BindView(R.id.tv_more_recommend)
    TextView tvMoreRecommend;

    @BindView(R.id.iv_item_avatar_1)
    ImageView ivItemAvatar1;
    @BindView(R.id.iv_item_avatar_2)
    ImageView ivItemAvatar2;
    @BindView(R.id.iv_item_avatar_3)
    ImageView ivItemAvatar3;
    @BindView(R.id.iv_item_avatar_4)
    ImageView ivItemAvatar4;

    @BindView(R.id.tv_item_sex_age_1)
    TextView tvItemSA1;
    @BindView(R.id.tv_item_sex_age_2)
    TextView tvItemSA2;
    @BindView(R.id.tv_item_sex_age_3)
    TextView tvItemSA3;
    @BindView(R.id.tv_item_sex_age_4)
    TextView tvItemSA4;

    private ArrayList<ImageView> avatars = new ArrayList<>(4);
    private ArrayList<TextView> mSAs = new ArrayList<>(4);

    private int type;

    private String sex;

    public static DTFragment getInstance(int type) {
        DTFragment fragment = new DTFragment();
        fragment.type = type;
        return fragment;
    }

    Unbinder unbinder;

    @Override
    protected View initViews(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = layoutInflater.inflate(R.layout.fragment_dt_layout, viewGroup, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        init();
        initSrl();
        initRecommendViews();
        return view;
    }

    private Dialog mShareDialog;

    private void initShareDialog(String path, int pos) {
        String memberId = SharedHelper.readId(mContext);
        String listMemberId = mList.get(pos).getMemberId();
        int type = 1;
        if (listMemberId.equals(memberId)) {
            type = 2;
        }
        mShareDialog = DialogUtil.getInstance().showShareDialog(mContext, type);
        DialogUtil.getInstance().setOnShareClickListener(new DialogUtil.OnShareClickListener() {
            @Override
            public void qqOnClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id", mList.get(pos).getId());
                bundle.putString("image", path);
                bundle.putString("title", mList.get(pos).getMemberName());
                bundle.putString("content", mList.get(pos).getContent());
                bundle.putInt("type", 0);
                RxActivityTool.skipActivity(mContext, ShareMemberActivity.class, bundle);
                mShareDialog.dismiss();
            }

            @Override
            public void circleOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWechatMoments(path, HttpMethods.SHARE_TITLE, mList.get(pos).getContent(), HttpMethods.SHARE_URL);
            }

            @Override
            public void qZoneOnClick(View v) {
                mShareDialog.dismiss();
                //删除操作
                deleteDongTai(pos);
            }

            @Override
            public void weixinOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWeChat(path, HttpMethods.SHARE_TITLE, mList.get(pos).getContent(), HttpMethods.SHARE_URL);
//
            }

            @Override
            public void jubaoOnClick(View v) {
                mShareDialog.dismiss();
                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("type","0");
                RxActivityTool.skipActivity(mContext, ReleaseJuBaoAcctivity.class,bundle);

            }
        });
        mShareDialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(MessageEvent messageEvent) {
        if (messageEvent.getTag().equals(EventTag.DT)) {
            refresh();
        }
    }


    private String city;

    public void refresh() {
        isShowDialog = false;
        page = 1;
        mList.clear();
        mAdapter.notifyDataSetChanged();
        initData();
    }

    public void updateDongTai(DTBean obj) {
        if (mList != null) {
            //type 0--打招呼；1--修改其他信息
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).getId().equals(obj.getId())) {
                    mAdapter.setData(i, obj);
                    break;
                }
            }
        }
    }

    public void shaixuan(String sex) {
        this.sex = sex;
        refresh();
    }

    public void deleteDongTai(DTBean obj) {
        if (mList != null) {
            //type 0--打招呼；1--修改其他信息
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).getId().equals(obj.getId())) {
                    mList.remove(i);
                    mAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    public void updateDaCall(String memberId, int sfdc) {
        //type 0--打招呼；1--修改其他信息
        if (mList != null) {
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).getMemberId().equals(memberId)) {
                    mList.get(i).setSfdc(sfdc);
                    mAdapter.notifyItemChanged(i);
                }
            }
        }
    }

    private void initSrl() {
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlAll.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            isShowDialog = false;
            page++;
            initData();
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            initData();
        }
    }

    private List<DTBean> mList;
    private DTAdapter mAdapter;

    private void init() {
        mList = new ArrayList<>();
        ((SimpleItemAnimator) recMain.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recMain.setLayoutManager(linearLayoutManager);
        mAdapter = new DTAdapter(R.layout.item_dt, mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnImageClickListener(new DTAdapter.OnImageClickListener() {
            @Override
            public void onItemClick(View view, int c_pos, int f_pos) {
//                PictureSelector.create(mContext)
//                        .themeStyle(R.style.picture_default_style)
//                        .isNotPreviewDownload(true)
//                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
//                        .openExternalPreview(c_pos, mList.get(f_pos).getMediaList());
                Bundle bundle = new Bundle();
                bundle.putInt("item", c_pos);
                bundle.putSerializable("listPath", (Serializable) mList.get(f_pos).getImgs());
                RxActivityTool.skipActivity(getActivity(), NetPicShowActivity.class, bundle);

            }
        });

        tv_qkq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getActivity().startActivity(settingsIntent);
            }
        });
    }

    private List<MemberBean> mbList;

    private void getTuiJianList() {
        SubscriberOnNextListener<BaseBean<List<MemberBean>>> onNextListener = baseBean -> {
            mbList = baseBean.getData();
            for (int i = 0; i < avatars.size(); i++) {
                RequestOptions options = new RequestOptions()
                        .placeholder(R.mipmap.img_default)//图片加载出来前，显示的图片
                        .fallback(R.mipmap.img_default) //url为空的时候,显示的图片
                        .error(R.mipmap.img_default)
                        .transform(new CenterCrop(), new RoundedCorners(40));//图片加载失败后，显示的图片
                Glide.with(mContext).load(mbList.get(i).getHeadPic()).apply(options).into(avatars.get(i));
                mSAs.get(i).setText(mbList.get(i).getAge());
            }
        };
        HttpMethods.getInstance().getTuiJianList(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog));
    }

    private int page = 1;
    private boolean isShowDialog = true;

    @Override
    protected void initData() {
        if(page == 1){
            getTuiJianList();
        }
        if (type == 2) {
            city = SharedHelper.readValueByKeyForString(getContext(), "city");
            if (StringUtil.isEmpty(city) && GpsUtil.isOPen(getContext())) {
                inviteLinear.setVisibility(View.VISIBLE);
                return;
            } else {
                inviteLinear.setVisibility(View.GONE);
            }
        }
        SubscriberOnNextListener<BaseBean<List<DTBean>>> onNextListener = baseBean -> {
            if (baseBean.getData().isEmpty() && page == 1) {
                none.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
                srlAll.setEnableLoadmore(false);
            } else {
                none.setVisibility(View.INVISIBLE);
                mList.addAll(baseBean.getData());
                for (int i = 0; i < mList.size(); i++) {
                    String imgs[] = mList.get(i).getPicList().split(",");
                    List<String> list = new ArrayList<>();
                    List<LocalMedia> mediaList = new ArrayList<>();
                    for (int j = 0; j < imgs.length; j++) {
                        LocalMedia localMedia = new LocalMedia();
                        list.add(imgs[j]);
                        localMedia.setPath(imgs[j]);
                        mediaList.add(localMedia);

                    }
                    mList.get(i).setImgs(list);
                    mList.get(i).setMediaList(mediaList);
                }
                mAdapter.notifyDataSetChanged();
                if (baseBean.getData().size() < 10) {
                    srlAll.setEnableLoadmore(false);
                } else {
                    srlAll.setEnableLoadmore(true);
                }
            }
        };

        String lat = SharedHelper.readValueByKeyForString(mContext, "lat");
        String lng = SharedHelper.readValueByKeyForString(mContext, "lng");
        DTModel dtModel = new DTModel(page, 0, SharedHelper.readId(mContext), lat, lng, city, sex);//登录上传参数
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        switch (type) {
            case 0:
                HttpMethods.getInstance().dt_list(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
                ll_recommend.setVisibility(View.VISIBLE);
                break;
            case 1:
                HttpMethods.getInstance().dt_gz_list(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
                break;
            case 2:
                HttpMethods.getInstance().tcListDynamic(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
                break;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.zanLinear:
                httpLike(position);
                break;
            case R.id.iv_logo:
                if (mList.get(position).getMemberId().equals(SharedHelper.readId(mContext))) {
                    RxActivityTool.skipActivity(mContext, PeopleMsgActivity.class);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mList.get(position).getMemberId());
                    RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class, bundle);
                }
                break;
            case R.id.tv_say_hello:
                if (mList.get(position).getSfdc() == 1) {
                    return;
                }
                if (SharedHelper.readId(mContext).equals(mList.get(position).getMemberId())) {
                    RxToast.normal("不能给自己打招呼");
                } else {
                    httpSayHello(position);
                }
                break;
            case R.id.iv_share:
                if (!mList.get(position).getImgs().get(0).isEmpty()) {
                    initShareDialog(mList.get(position).getImgs().get(0), position);
                } else {
                    initShareDialog("", position);
                }

                break;
        }
    }

    private void httpSayHello(int position) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("打招呼成功");
            updateDaCall(mList.get(position).getMemberId(), 1);
            mList.get(position).setSfdc(1);
            sendBroadcastToMain(0, position);
            RxToast.normal(baseBean.getMsg());
        };
        SayModel userModel = new SayModel();
        userModel.setMemberId(SharedHelper.readId(mContext));
        userModel.setOtherMemberId(mList.get(position).getMemberId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().callMember(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    public void sendBroadcastToMain(int type, int postion) {
        MainActivity mainActivity = (MainActivity) getActivity();
        if (type == 0) {
            //打招呼
            mainActivity.updateDaCall(mList.get(postion).getMemberId(), mList.get(postion).getSfdc());
        } else {
            mainActivity.updateDongTai(mList.get(postion));
        }
    }

    private static final String TAG = "DTFragment";

    private void httpLike(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            Log.d(TAG, "onNext: " + baseBean.toString());
            if (mList.get(pos).getSfdz() == 0) {
                mList.get(pos).setSfdz(1);
                mList.get(pos).setZanNum(mList.get(pos).getZanNum() + 1);
            } else {
                mList.get(pos).setSfdz(0);
                mList.get(pos).setZanNum(mList.get(pos).getZanNum() - 1);
            }
            sendBroadcastToMain(1, pos);
//            mAdapter.notifyItemChanged(pos);
            RxToast.normal(baseBean.getMsg());
        };
        ZanModel zanModel = new ZanModel();
        zanModel.setBdzId(mList.get(pos).getId());
        zanModel.setDzrId(SharedHelper.readId(mContext));
        zanModel.setType(0);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(zanModel));
        HttpMethods.getInstance().saveDianZan(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = new Intent(mContext, DTmsgActivity.class);
        Bundle bundle_2 = new Bundle();
        bundle_2.putParcelable("dt", mList.get(position));
        bundle_2.putInt("position", position);
        intent.putExtras(bundle_2);
        mContext.startActivity(intent);
    }

    private void deleteDongTai(int position) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                RxToast.normal("删除成功！");
                mList.remove(position);
                mAdapter.notifyDataSetChanged();
            }
        };

        Map<String, Object> params = new HashMap<>();
        params.put("id", mList.get(position).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().deleteDongTai(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    @OnClick({R.id.tv_more_recommend,R.id.iv_item_avatar_1,R.id.iv_item_avatar_2,R.id.iv_item_avatar_3,R.id.iv_item_avatar_4})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.tv_more_recommend:
                RxActivityTool.skipActivity(getActivity(), RecommendedInteractiveActivity.class,bundle);
                break;
            case R.id.iv_item_avatar_1:
                bundle.putString("id",mbList.get(0).getId());
                RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class,bundle);
                break;
            case R.id.iv_item_avatar_3:
                bundle.putString("id",mbList.get(2).getId());
                RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class,bundle);
                break;
            case R.id.iv_item_avatar_2:
                bundle.putString("id",mbList.get(1).getId());
                RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class,bundle);
                break;
            case R.id.iv_item_avatar_4:
                bundle.putString("id",mbList.get(3).getId());
                RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class,bundle);
                break;
        }

    }

    private void initRecommendViews() {
        avatars.add(ivItemAvatar1);
        avatars.add(ivItemAvatar2);
        avatars.add(ivItemAvatar3);
        avatars.add(ivItemAvatar4);

        mSAs.add(tvItemSA1);
        mSAs.add(tvItemSA2);
        mSAs.add(tvItemSA3);
        mSAs.add(tvItemSA4);
    }


    private void requestRecommendList() {

    }

    private void notifyRecommendList() {
    }


}
